<?php
namespace Platform\Domain;

use Platform\Common\Functions;
use Platform\Model\SystemMenu as MenuModel;
use Platform\Model\SystemMenuRole as SystemMenuRoleModel;
use Platform\Model\AdminRole as AdminRoleModel;
use PhalApi\Exception\BadRequestException;

class Menu extends Functions{

    //获取所有菜单
    public function menuList() {
        $model = new MenuModel();
        $SystemMenuRoleModel = new SystemMenuRoleModel();
        if( $this->tokenData['role_id'] != 1 ){
            $where = array('mr.role_id'=>$this->tokenData['role_id'],'delete_flag'=>'N');
            $select = 'm.id,m.id as authorityId,m.title,m.name,m.sort_num,m.parent_id as parentId,m.icon,m.path,m.url,m.depth';
            $order = 'm.parent_id, m.sort_num';
            $menus = $SystemMenuRoleModel->getRoleMenuList($where,$select,$order);
        }else{
            $menus = $model->listAllMenus();
        }
        //根据parentId分子类
        $menus = $this->_getTree($menus);
        return $menus;
    }
    //获取添加/编辑时需要的菜单列表
    public function selectMenuList() {
        $model = new MenuModel();
        $SystemMenuRoleModel = new SystemMenuRoleModel();
        if( $this->tokenData['role_id'] != 1 ){
            $where = array('mr.role_id'=>$this->tokenData['role_id']);
            $select = 'm.id,m.id as authorityId,m.title,m.name,m.sort_num,m.parent_id as parentId,m.icon,m.path,m.url,m.depth';
            $order = 'm.parent_id, m.sort_num';
            $menus = $SystemMenuRoleModel->getRoleMenuList($where,$select,$order);
        }else{
            $menus = $model->listAllMenus();
        }
        //将权限人变成数组
        foreach ( $menus as $k => $v ){
            //根据depth深度来渲染要展示的内容
            if( $v['depth'] == 0 ){//顶级菜单
                $menus[$k]['title'] = '|-'.$v['title'];
            }else{
                $str = '';
                for ( $i=1;$i<=$v['depth'];$i++ ){
                    $str .= '|- ';
                }
                $menus[$k]['title'] = $str.'|-'.$v['title'];
            }
        }
        $menus = $this->_getTree($menus);
        return $menus;
    }
    //菜单获取当前角色列表
    public function getRoleList(){
        $model = new AdminRoleModel();
        $where = array();
        $where['not id'] = array(1);
        $where['delete_flag'] = 'N';
        $select = "role_name,id";
        $list = $model->getList($where,array(0),$select);
        return $list;
    }
    //添加菜单
    public function addMenu($insertData){
        $model = new MenuModel();
        $SystemMenuRoleModel = new SystemMenuRoleModel();
        //查询当前编号是否已存在
        $menuData = $model->getData(array('url'=>$insertData['url']));
        if( !empty($menuData)&&$menuData['delete_flag']=='N' ){
            throw new BadRequestException('该菜单路径已存在！');
        }
        //涉及多条数据同时插入，需要再新建一个数组
        $allInsertData = array();
        $n = 0;
        //①添加菜单信息
        $role_ids = array();
        if( !empty( $insertData['role_ids'] ) ){
            $role_ids = explode(',',$insertData['role_ids']);
        }
        unset($insertData['role_ids']);
        //处理深度 todo 现阶段只支持二级
        if( $insertData['parent_id'] != 0 ){
            $insertData['depth'] = 1;
        }
        //获取固定的参数
        $insertData = $this->selfAddFields($insertData);
        //因为涉及数据表多步操作，所以要开启事务
        \PhalApi\DI()->notorm->beginTransaction('db_master');
        $res = $model->insert($insertData);
        if( $res === false ){
            \PhalApi\DI()->notorm->rollback('db_master');//回滚
            throw new BadRequestException('菜单添加错误，请联系管理员！');
        }
        //②处理角色信息只有子级菜单才能进行角色关联操作
        if( count($role_ids)>0 && $insertData['parent_id'] != 0 ){
            //如果菜单为子级，要判断当前父级菜单是否含有权限，没有的话要赋值上去！！！
            foreach ( $role_ids as $k => $v ){
                $parentInfo = $SystemMenuRoleModel->getData(array('menu_id'=>$insertData['parent_id'],'role_id'=>$v));
                if( empty( $parentInfo ) ){//没有，加上
                    $allInsertData[$n]['menu_id'] = $insertData['parent_id'];
                    $allInsertData[$n]['role_id'] = $v;
                    $allInsertData[$n]['parent_id'] = $insertData['parent_id'];
                    $n++;
                }
                $allInsertData[$n]['menu_id'] = $res;
                $allInsertData[$n]['role_id'] = $v;
                $allInsertData[$n]['parent_id'] = $insertData['parent_id'];
                $n++;
            }
            //添加到关联表中
            $res = $SystemMenuRoleModel->insertMore($allInsertData);
            if( $res === false ){
                \PhalApi\DI()->notorm->rollback('db_master');//回滚
                throw new BadRequestException('同步角色菜单失败，请联系管理员');
            }
        }
        \PhalApi\DI()->notorm->commit('db_master');//提交
        return $res;
    }
    //获取菜单详情
    public function menuDetail($id,$select){
        $model = new MenuModel();
        $SystemMenuRoleModel = new SystemMenuRoleModel();
        $menuData = $model->getData(array('id'=>$id),array(),$select);
        if( empty($menuData)&&$menuData['delete_flag']=='Y' ){
            throw new BadRequestException('菜单不存在或已删除！');
        }
        //根据id查询关联表数据
        $role_ids = $SystemMenuRoleModel->getList(array('menu_id'=>$id));
        if( !empty( $role_ids ) ){
            foreach ( $role_ids as $k => $v ){
                $menuData['role_id'][$k] = $v['role_id'];
            }
        }else{
            $menuData['role_id'] = array();
        }
        return $menuData;
    }
    //编辑提交菜单
    public function updateMenu($id,$updateData){
        $model = new MenuModel();
        $SystemMenuRoleModel = new SystemMenuRoleModel();
        //查询当前编号是否已存在
        $menuData = $model->getData(array('url'=>$updateData['url']));
        if( !empty($menuData)&&$menuData['delete_flag']=='N'&&$menuData['id'] != $id ){
            throw new BadRequestException('该菜单路径已存在！');
        }
        //涉及多条数据同时插入，需要再新建一个数组
        $allInsertData = array();
        $n = 0;
        //①添加菜单信息
        $role_ids = array();
        if( !empty( $updateData['role_ids'] ) ){
            $role_ids = explode(',',$updateData['role_ids']);
        }
        //处理角色信息只有子级菜单才能进行角色关联操作
        unset($updateData['role_ids']);
        //处理深度 todo 现阶段只支持二级
        if( $updateData['parent_id'] != 0 ){
            $updateData['depth'] = 1;
        }
        //获取固定的参数
        $updateData = $this->selfEditFields($updateData);
        //因为涉及数据表多步操作，所以要开启事务
        \PhalApi\DI()->notorm->beginTransaction('db_master');
        $res = $model->update($id,$updateData);
        if( $res === false ){
            \PhalApi\DI()->notorm->rollback('db_master');//回滚
            throw new BadRequestException('菜单编辑提交错误，请联系管理员！');
        }
        //只是增加/删除了管理员
        if( count($role_ids)>0 && $updateData['parent_id'] != 0 ){
            //②处理角色信息 清除角色底下所有的关联信息重新添加，避免出问题
            $res = $SystemMenuRoleModel->deleteAll(array('menu_id'=>$id));
            if( $res === false ){
                \PhalApi\DI()->notorm->rollback('db_master');//回滚
                throw new BadRequestException('菜单关联关系清除错误，请联系管理员！');
            }
            //如果菜单为子级，要判断当前父级菜单是否含有权限，没有的话要赋值上去！！！
            foreach ( $role_ids as $k => $v ){
                $parentInfo = $SystemMenuRoleModel->getData(array('menu_id'=>$updateData['parent_id'],'role_id'=>$v));
                if( empty( $parentInfo ) ){//没有，加上
                    $allInsertData[$n]['menu_id'] = $updateData['parent_id'];
                    $allInsertData[$n]['role_id'] = $v;
                    $allInsertData[$n]['parent_id'] = $updateData['parent_id'];
                    $n++;
                }
                $allInsertData[$n]['menu_id'] = $id;
                $allInsertData[$n]['role_id'] = $v;
                $allInsertData[$n]['parent_id'] = $updateData['parent_id'];
                $n++;
            }
            //添加到关联表中
            $res = $SystemMenuRoleModel->insertMore($allInsertData);
            if( $res === false ){
                \PhalApi\DI()->notorm->rollback('db_master');//回滚
                throw new BadRequestException('同步角色菜单失败，请联系管理员');
            }
            //根据菜单筛选现在的所有角色
            $old_menu_info = $SystemMenuRoleModel->getList(array('menu_id'=>$updateData['parent_id']));
            if( !empty( $old_menu_info ) ){
                foreach ( $old_menu_info as $k => $v ){
                    //③清除只有顶级菜单权限的角色id
                    $old_role_count = $SystemMenuRoleModel->count(array('parent_id'=>$updateData['parent_id'],'role_id'=>$v['role_id']),'id');
                    if( $old_role_count == 1 ){
                        $res = $SystemMenuRoleModel->deleteAll(array('menu_id'=>$updateData['parent_id'],'role_id'=>$v['role_id'],'parent_id'=>$updateData['parent_id']));
                        if( $res === false ){
                            \PhalApi\DI()->notorm->rollback('db_master');//回滚
                            throw new BadRequestException('同步角色顶级菜单失败，请联系管理员');
                        }
                    }
                }
            }
        }
        \PhalApi\DI()->notorm->commit('db_master');//提交
        return $res;
    }
    //删除
    public function deleteMenu($id){
        $model = new MenuModel();
        $SystemMenuRoleModel = new SystemMenuRoleModel();
        $info = $model->getData(array('id'=>$id));
        if( empty( $info ) ){
            throw new BadRequestException('数据不存在！');
        }
        if( $info['delete_flag'] =='Y' ){
            throw new BadRequestException('数据已被删除！');
        }
        //①删除菜单信息
        //获取固定的参数
        $updateData = $this->selfDeleteFields(array());
        //因为涉及数据表多步操作，所以要开启事务
        \PhalApi\DI()->notorm->beginTransaction('db_master');
        $res = $model->updateAll(array('id'=>$id),$updateData);
        if( $res === false ){
            \PhalApi\DI()->notorm->rollback('db_master');//回滚
            throw new BadRequestException('主数据删除有误，请联系管理员！');
        }
        //②判断是不是顶级菜单，是的话子级全部删除+角色菜单父级为菜单的也要清空
        if( $info['parent_id'] != 0 ){
            //删除所有子菜单
            $updateData = $this->selfDeleteFields(array());
            $res = $model->updateAll(array('parent_id'=>$id),$updateData);
            if( $res === false ){
                \PhalApi\DI()->notorm->rollback('db_master');//回滚
                throw new BadRequestException('子菜单数据删除有误，请联系管理员！');
            }
        }else{
            //删除所有子菜单关联的角色
            $res = $model->deleteAll(array('parent_id'=>$id));
            if( $res === false ){
                \PhalApi\DI()->notorm->rollback('db_master');//回滚
                throw new BadRequestException('菜单关联数据删除有误，请联系管理员！');
            }
            $res = $SystemMenuRoleModel->deleteAll(array('menu_id'=>$id));
            if( $res === false ){//删除角色菜单关联关系
                \PhalApi\DI()->notorm->rollback('db_master');//回滚
                throw new BadRequestException('角色关联数据删除有误，请联系管理员！');
            }
        }
        \PhalApi\DI()->notorm->commit('db_master');//提交
        return $res;
    }
}
